package com.permission_server.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.permission_server.util.HandlerException.HandlerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;
import java.util.ArrayList;

@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {

    @Autowired
    HandlerException handlerException;

    @Value("${prop.upload-folder}")
    private String UPLOAD_FOLDER;

    static final ArrayList<String> EXCLUDE_PATTERN = new ArrayList<>();
    static final ArrayList<String> ALLOW_ORIGINS = new ArrayList<>();

    static {
        EXCLUDE_PATTERN.add("/login/doLogin");
        EXCLUDE_PATTERN.add("/login/doRegister");
        EXCLUDE_PATTERN.add("/uploadPhoto/**");

        EXCLUDE_PATTERN.add("/swagger-resources/**");
        EXCLUDE_PATTERN.add("/webjars/**");
        EXCLUDE_PATTERN.add("/v2/**");
        EXCLUDE_PATTERN.add("/swagger-ui.html/**");
        EXCLUDE_PATTERN.add("/doc.html/**");
        EXCLUDE_PATTERN.add("/v2/api-docs/**");


        ALLOW_ORIGINS.add("http://localhost:3000");
        ALLOW_ORIGINS.add("http://127.0.0.1:3000");
    }


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        File dest = new File(UPLOAD_FOLDER);
        //windows、linux通用
        registry.addResourceHandler("/uploadPhoto/**").addResourceLocations("file:" + dest.getAbsolutePath() + "/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * 全局过滤器
     *
     * @return
     */
    @Bean
    public SaServletFilter saServletFilter() {
        SaServletFilter saServletFilter = new SaServletFilter();

        // 指定 拦截路由 与 放行路由
        saServletFilter.addInclude("/**");
        saServletFilter.addExclude("/favicon.ico");

        // 认证函数: 每次请求执行
        saServletFilter.setAuth(authRun -> {
            SaRouter.match("/**").notMatch(EXCLUDE_PATTERN).check(check -> {
                try {
                    StpUtil.checkLogin();
                } catch (NotLoginException e) {
                    check.back(handlerException.handlerNotLogin(e));
                }
            });
        });

        // 前置函数：在每次认证函数之前执行
        saServletFilter.setBeforeAuth(run -> {
            // 查看跨域请求的地址
            //System.out.println(SaHolder.getRequest().getHeader("Origin"));
            String origin = SaHolder.getRequest().getHeader("Origin");
            // ---------- 设置跨域响应头 ----------
            if (ALLOW_ORIGINS.contains(origin)) {
                // 允许指定域访问跨域资源
                SaHolder.getResponse().setHeader("Access-Control-Allow-Origin", origin);
            }
            SaHolder.getResponse()
                    // 允许所有请求方式
                    .setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE")
                    // 有效时间
                    .setHeader("Access-Control-Max-Age", "3600")
                    // 允许的header参数
                    .setHeader("Access-Control-Allow-Headers", "*");
        });
        return saServletFilter;
    }
}
